package com.acmen.easyapi.repository;

import com.acmen.easyapi.dbcp.JdbcService;
import com.acmen.easyapi.model.CallResult;
import com.acmen.easyapi.model.CustomizePage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author acmen
 */
@Component
public class CallResultRepository {

    private final static String COUNT_SQL = "select count(*) from t_call_result where report_id=?";
    private final static String QUERY_PAGE_SQL = "select * from t_call_result where report_id=? order by begin_time limit ?,?";

    private final static String QUERY_SQL = "select * from t_call_result where report_id=? order by begin_time";
    private final static String INSERT_SQL = "insert into t_call_result(id,report_id,api_id,test_name,cost,send_size,receive_size,response_success,business_success,headers,params,body,expect_response,result,begin_time) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    private final static String DELETE_SQL = "delete from t_call_result where report_id=?";
    @Resource
    private JdbcService jdbcService;


    public CustomizePage<CallResult> selectPage(String reportId, int pageSize, int pageNo) {
        long count = jdbcService.count(COUNT_SQL,new Object[]{reportId});
        int start = (pageNo-1)*pageSize;
        int end = pageNo*pageSize;
        List<CallResult> callResults = jdbcService.selectList(QUERY_PAGE_SQL,new Object[]{reportId,start,end},CallResult.class);
        CustomizePage page = new CustomizePage();
        page.setRecords(callResults);
        page.setTotal(count);
        return page;
    }

    /**
     * 根据ID查询出记录
     *
     * @param reportId
     * @return
     */
    public List<CallResult> selectList(String reportId) {
        List<CallResult> callResults = jdbcService.selectList(QUERY_SQL, new Object[]{reportId,CallResult.class});
        return callResults;
    }

    /**
     * 保存结果
     *
     * @param callResults
     * @return
     */
    public void batchCreate(List<CallResult> callResults) {
        List<Object[]> batchArgs = new ArrayList<>();
        callResults.forEach(callResult -> {
            Object[] args = {callResult.getId(), callResult.getReportId(),
                    callResult.getApiId(), callResult.getTestName(),callResult.getCost(), callResult.getSendSize(),
                    callResult.getReceiveSize(),
                    callResult.isResponseSuccess(),callResult.isBusinessSuccess(),callResult.getHeaders(), callResult.getParams(),callResult.getBody(),
                    callResult.getExpectResponse(),callResult.getResult(), callResult.getBeginTime()};
            batchArgs.add(args);
        });
        jdbcService.batchUpdate(INSERT_SQL, batchArgs);
    }

    /**
     * 删除组合测试
     *
     * @param reportId
     * @return
     */
    public boolean deleteByReportId(String reportId) {
        return jdbcService.update(DELETE_SQL, new Object[]{reportId}) > 0;
    }

}
